package org.example.controller;

import org.example.entity.Device;
import org.example.entity.DeviceControlLog;
import org.example.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 设备控制器
 */
@RestController
@RequestMapping("/devices")
@CrossOrigin(origins = "*")
public class DeviceController {
    
    @Autowired
    private DeviceService deviceService;
    
    /**
     * 创建设备
     */
    @PostMapping
    public ResponseEntity<?> createDevice(@Valid @RequestBody Device device) {
        try {
            Device createdDevice = deviceService.createDevice(device);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdDevice);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取设备
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getDeviceById(@PathVariable Long id) {
        Optional<Device> device = deviceService.findById(id);
        if (device.isPresent()) {
            return ResponseEntity.ok(device.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据用户ID获取设备
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Device>> getDevicesByUserId(@PathVariable Long userId) {
        try {
            System.out.println("获取用户设备 - 用户ID: " + userId);
            List<Device> devices = deviceService.findByUserId(userId);
            System.out.println("找到设备数量: " + (devices != null ? devices.size() : "null"));
            return ResponseEntity.ok(devices);
        } catch (Exception e) {
            System.err.println("获取用户设备失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        }
    }
    
    /**
     * 根据房间获取设备
     */
    @GetMapping("/user/{userId}/room/{room}")
    public ResponseEntity<List<Device>> getDevicesByRoom(@PathVariable Long userId, @PathVariable String room) {
        List<Device> devices = deviceService.findByUserIdAndRoom(userId, room);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 根据设备类型获取设备
     */
    @GetMapping("/user/{userId}/type/{deviceTypeId}")
    public ResponseEntity<List<Device>> getDevicesByType(@PathVariable Long userId, @PathVariable Long deviceTypeId) {
        List<Device> devices = deviceService.findByUserIdAndDeviceTypeId(userId, deviceTypeId);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 根据状态获取设备
     */
    @GetMapping("/user/{userId}/status/{status}")
    public ResponseEntity<List<Device>> getDevicesByStatus(@PathVariable Long userId, @PathVariable Integer status) {
        List<Device> devices = deviceService.findByUserIdAndStatus(userId, status);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 根据在线状态获取设备
     */
    @GetMapping("/user/{userId}/online/{isOnline}")
    public ResponseEntity<List<Device>> getDevicesByOnlineStatus(@PathVariable Long userId, @PathVariable Integer isOnline) {
        List<Device> devices = deviceService.findByUserIdAndIsOnline(userId, isOnline);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 搜索设备
     */
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<List<Device>> searchDevices(@PathVariable Long userId, @RequestParam String name) {
        List<Device> devices = deviceService.searchDevicesByName(userId, name);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 获取用户所有房间
     */
    @GetMapping("/user/{userId}/rooms")
    public ResponseEntity<List<String>> getUserRooms(@PathVariable Long userId) {
        List<String> rooms = deviceService.getUserRooms(userId);
        return ResponseEntity.ok(rooms);
    }
    
    /**
     * 更新设备信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDevice(@PathVariable Long id, @Valid @RequestBody Device device) {
        try {
            device.setId(id);
            Device updatedDevice = deviceService.updateDevice(device);
            return ResponseEntity.ok(updatedDevice);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 控制设备开关
     */
    @PutMapping("/{id}/control")
    public ResponseEntity<?> controlDevice(@PathVariable Long id, @RequestBody DeviceControlRequest request) {
        try {
            System.out.println("设备控制请求 - 设备ID: " + id + ", 用户ID: " + request.getUserId() + 
                             ", 状态: " + request.getStatus() + ", 操作: " + request.getAction());
            Device device = deviceService.controlDevice(id, request.getUserId(), request.getStatus(), request.getAction());
            return ResponseEntity.ok(device);
        } catch (RuntimeException e) {
            System.err.println("设备控制失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 更新设备在线状态
     */
    @PutMapping("/{id}/online")
    public ResponseEntity<?> updateDeviceOnlineStatus(@PathVariable Long id, @RequestBody OnlineStatusRequest request) {
        try {
            Device device = deviceService.updateDeviceOnlineStatus(id, request.getIsOnline());
            return ResponseEntity.ok(device);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 更新设备属性
     */
    @PutMapping("/{id}/properties")
    public ResponseEntity<?> updateDeviceProperties(@PathVariable Long id, @RequestBody PropertiesRequest request) {
        try {
            System.out.println("设备属性更新请求 - 设备ID: " + id);
            System.out.println("请求数据: " + request);
            System.out.println("属性内容: " + request.getProperties());
            
            Device device = deviceService.updateDeviceProperties(id, request.getProperties());
            System.out.println("设备属性更新成功: " + device.getName());
            return ResponseEntity.ok(device);
        } catch (RuntimeException e) {
            System.err.println("设备属性更新失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            System.err.println("设备属性更新异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }
    
    /**
     * 获取设备控制记录
     */
    @GetMapping("/{id}/logs")
    public ResponseEntity<List<DeviceControlLog>> getDeviceControlLogs(@PathVariable Long id) {
        List<DeviceControlLog> logs = deviceService.getDeviceControlLogs(id);
        return ResponseEntity.ok(logs);
    }
    
    /**
     * 分页获取设备控制记录
     */
    @GetMapping("/{id}/logs/page")
    public ResponseEntity<Page<DeviceControlLog>> getDeviceControlLogsPage(@PathVariable Long id, Pageable pageable) {
        Page<DeviceControlLog> logs = deviceService.getDeviceControlLogs(id, pageable);
        return ResponseEntity.ok(logs);
    }
    
    /**
     * 统计用户设备数量
     */
    @GetMapping("/user/{userId}/count")
    public ResponseEntity<Long> getDeviceCount(@PathVariable Long userId) {
        long count = deviceService.countDevicesByUserId(userId);
        return ResponseEntity.ok(count);
    }
    
    /**
     * 统计在线设备数量
     */
    @GetMapping("/user/{userId}/online-count")
    public ResponseEntity<Long> getOnlineDeviceCount(@PathVariable Long userId) {
        long count = deviceService.countOnlineDevicesByUserId(userId);
        return ResponseEntity.ok(count);
    }
    
    /**
     * 删除设备
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDevice(@PathVariable Long id) {
        try {
            deviceService.deleteDevice(id);
            return ResponseEntity.ok("设备删除成功");
        } catch (RuntimeException e) {
            if ("设备不存在".equals(e.getMessage())) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
            }
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    // 内部类用于请求体
    public static class DeviceControlRequest {
        private Long userId;
        private Integer status;
        private String action;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Integer getStatus() { return status; }
        public void setStatus(Integer status) { this.status = status; }
        public String getAction() { return action; }
        public void setAction(String action) { this.action = action; }
    }
    
    public static class OnlineStatusRequest {
        private Integer isOnline;
        
        public Integer getIsOnline() { return isOnline; }
        public void setIsOnline(Integer isOnline) { this.isOnline = isOnline; }
    }
    
    public static class PropertiesRequest {
        private String properties;
        
        public String getProperties() { return properties; }
        public void setProperties(String properties) { this.properties = properties; }
    }
}
